﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using SpiderRelation0720.Help;

namespace SpiderRelation0720.WebSearch
{
    class WebSearch
    {
        public  string GetPageData(string url, string charSet,string cookie)
        {
            //获取页面信息
            string strWebData = string.Empty;
            if (url != null || url.Trim() != "")
            {
                WebClient myWebClient = new WebClient();
                //创建WebClient实例myWebClient
                // 需要注意的：
                //有的网页可能下不下来，有种种原因比如需要cookie,编码问题等等
                //这是就要具体问题具体分析比如在头部加入cookie
                myWebClient.Headers.Add("Cookie",cookie);
                // myWebClient.Headers.Add("请求", "GET /stu/newstu_index.jsp HTTP/1.1");
                myWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; MAAU");
                //这样可能需要一些重载方法。根据需要写就可以了
                //获取或设置用于对向 Internet 资源的请求进行身份验证的网络凭据。
                myWebClient.Credentials = CredentialCache.DefaultCredentials;
                //如果服务器要验证用户名,密码
                //NetworkCredential mycred = new NetworkCredential("2010302580222", "19920501");
                //myWebClient.Credentials = mycred;
                //从资源下载数据并返回字节数组。（加@是因为网址中间有"/"符号）
                byte[] myDataBuffer = myWebClient.DownloadData(url);
                strWebData = Encoding.Default.GetString(myDataBuffer);
                //获取网页字符编码描述信息
                Match charSetMatch = Regex.Match(strWebData, "<meta([^<]*)charset=([^<]*)\"", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                string webCharSet = charSetMatch.Groups[2].Value;
                if (charSet == null || charSet == "")
                {
                    //如果未获取到编码，则设置默认编码
                    if (webCharSet == null || webCharSet == "")
                    {
                        charSet = "UTF-8";
                    }
                    else
                    {
                        charSet = webCharSet;
                    }
                }
                if (charSet != null && charSet != "" && Encoding.GetEncoding(charSet) != Encoding.Default)
                {
                    strWebData = Encoding.GetEncoding(charSet).GetString(myDataBuffer);
                }
            }
            return strWebData;
        }
        public List<RCourseRecord> Anaylze(string text)//对文本文件进行正则表达式匹配
        {
            string classPP = @"周(.*?):(\d)-(\d*)周(.*?)\n(\d*)-(\d*)节,(\d)区,(\d)-((\d).*?);";
            Regex r = new Regex(classPP);
            Match classes = r.Match(text);
            List<RCourseRecord> classesList = new List<RCourseRecord>();
            while (classes.Success)
            {
                //Console.WriteLine("Match" + (++matchCount));
                RCourseRecord temp = new RCourseRecord();
                Group dayOfWeek = classes.Groups[1];
                int dayofweek = GetWeekNumber(dayOfWeek.ToString());
                if (dayofweek < 0)
                {
                    break;      //星期不合法，跳出此次插入值
                }
                temp.dayOfTheWeek =byte.Parse(dayofweek .ToString());//上课星期(1~7)
                Group weekStart = classes.Groups[2];
                temp.startOfWeek  = byte.Parse(weekStart.ToString());   //课程开始周数(1~18)
                Group weekEnd = classes.Groups[3];
                temp.endOfWeek  = byte.Parse(weekEnd.ToString());   //课程结束周数(1~18)
                Group classStart = classes.Groups[5];
                temp.startNumberOfClass = byte.Parse(classStart.ToString());    //课程开始时间（1~12）
                Group classEnd = classes.Groups[6];
                temp.endNumberOfClass = byte.Parse(classEnd.ToString());    //课程结束的时间（1~12)
                Group classArea = classes.Groups[7];
                temp.area = byte.Parse(classArea.ToString());   //小区编号(1,2,3)
                Group classBuilding = classes.Groups[8];
                temp.buildingMark =classBuilding.ToString();    //教学楼编号(string)(1,2,理,等等)
                Group classFloor = classes.Groups[10];
                temp.floorNumber = byte.Parse(classFloor.ToString());   //楼层数
                Group className = classes.Groups[9];
                temp.classRoom = int.Parse(className.ToString());   //教室编号
                //添加的返回列表中
                classesList.Add(temp);      
                classes = classes.NextMatch();
            }
            return classesList;
        }
        private int GetWeekNumber(string week)
        {
            switch (week)
            { 
                case "一":return 1;
                case "二": return 2;
                case "三": return 3;
                case "四": return 4;
                case "五": return 5;
                case "六": return 6;
                case "日": return 7;
            }
            return -1;
        }
    }
}
